#include "game.h"

LPDIRECT3DSURFACE9 kitty_image[7];
SPRITE kitty;
LPDIRECT3DSURFACE9 back;

long start = GetTickCount();

int Game_Init(HWND hwnd)
{
    char s[20];
    int n;

	srand(time(NULL));

    for (n=0; n<6; n++)
    {
        sprintf(s,"cat%d.bmp",n+1);
        kitty_image[n] = LoadSurface(s, D3DCOLOR_XRGB(255,0,255));
        if (kitty_image[n] == NULL)
            return 0;
    }

    back = LoadSurface("background.bmp", NULL );

    kitty.x = 100;
    kitty.y = 150;
    kitty.width = 96;
    kitty.height = 96;
    kitty.curframe = 0;
    kitty.lastframe = 5;
    kitty.animdelay = 2;
    kitty.animcount = 0;
    kitty.movex = 8;
    kitty.movey = 0;
    return 1;
}

void Game_Run(HWND hwnd)
{
    RECT rect;

    if (d3ddev == NULL)
        return;

        if (GetTickCount() - start >= 30)
        {
            start = GetTickCount();

            kitty.x += kitty.movex;
            kitty.y += kitty.movey;

            if (kitty.x > SCREEN_WIDTH - kitty.width)
                kitty.x = 0;
            if (kitty.x < 0)
                kitty.x = SCREEN_WIDTH - kitty.width;

            if (++kitty.animcount > kitty.animdelay)
            {
                kitty.animcount = 0;

                if (++kitty.curframe > kitty.lastframe)
                    kitty.curframe = 0;
            }
       }

        if (d3ddev->BeginScene())
        {
            d3ddev->StretchRect(back, NULL, backbuffer, NULL, D3DTEXF_NONE);

            rect.left = kitty.x;
            rect.top = kitty.y;
            rect.right = kitty.x + kitty.width;
            rect.bottom = kitty.y + kitty.height;

            d3ddev->StretchRect(kitty_image[kitty.curframe], NULL, backbuffer, &rect, D3DTEXF_NONE);

        d3ddev->EndScene();
    }

    d3ddev->Present(NULL, NULL, NULL, NULL);

    if (KEY_DOWN(VK_ESCAPE))
        PostMessage(hwnd, WM_DESTROY, 0, 0);

}

void Game_End(HWND hwnd)
{
    int n;

    for (n=0; n<6; n++)
        kitty_image[n]->Release();

    back->Release();
}

